package com.example.testdemo.pools;

import java.util.concurrent.LinkedBlockingQueue;

import com.example.testdemo.TankGameActivity;
import com.example.testdemo.kstatic.sprite.ShieldSprite;
import com.example.testdemo.manager.ResourcesManager;
import com.example.testdemo.resources.CharacterResources;
import com.example.testdemo.scenes.stage.BaseStage;

public class ShieldPools {

	private final int DEFAULT_SHEILD = 10;

	private static ShieldPools INSTANCE = null;
	private static BaseStage mOnScene = null;

	public static ShieldPools getInstance(TankGameActivity activity,
	        BaseStage onScene) {
		if (INSTANCE == null) {
			mOnScene = onScene;
			INSTANCE = new ShieldPools(activity);
		} else {
			if (onScene != mOnScene) {
				INSTANCE.free();
				mOnScene = onScene;
				INSTANCE = new ShieldPools(activity);
			}
		}

		return INSTANCE;
	}

	private TankGameActivity mActivity = null;

	private final LinkedBlockingQueue<ShieldSprite> mShieldQueue = new LinkedBlockingQueue<ShieldSprite>(
	        DEFAULT_SHEILD);

	private ShieldPools(TankGameActivity activity) {
		mActivity = activity;
		CharacterResources resources = (CharacterResources) ResourcesManager
		        .getInstance().getResources(
		                ResourcesManager.RESOURCES_CHARACTER);

		for (int i = 0; i < DEFAULT_SHEILD; i++) {
			ShieldSprite shield = new ShieldSprite(this, 0, 0,
			        resources.mShieldTextureRegion,
			        mActivity.getVertexBufferObjectManager());
			mOnScene.attachChild(shield);
			hideShield(shield);
			mShieldQueue.offer(shield);
		}
	}

	private void hideShield(ShieldSprite shield) {
		shield.setVisible(false);
	}

	private void showShield(ShieldSprite shield) {
		shield.setVisible(true);
	}

	public ShieldSprite pollOneSheild() {
		ShieldSprite shield = mShieldQueue.poll();
		mShieldQueue.offer(shield);
		showShield(shield);
		return shield;
	}

	public void recycle(ShieldSprite shield) {
		hideShield(shield);
	}

	public void free() {
		for (ShieldSprite shield : mShieldQueue) {
			mOnScene.detachChild(shield);
			shield.dispose();
		}
		mShieldQueue.clear();
	}
}
